'use strict';

goog.provide('Blockly.Arduino.Microduino');

goog.require('Blockly.Arduino');

Blockly.Arduino.NFC_Format = function() {
  Blockly.Arduino.definitions_['define_includes'] = '#include <Wire.h>\n'
 +'#include <Adafruit_NFCShield_I2C.h>\n';

  Blockly.Arduino.definitions_['define_options'] = '#define IRQ                     (2)\n'
 	 +'#define NR_SHORTSECTOR          (32)\n' 
 	 +'#define NR_LONGSECTOR           (8)\n'
 	 +'#define NR_BLOCK_OF_SHORTSECTOR (4)\n'
 	 +'#define NR_BLOCK_OF_LONGSECTOR  (16)\n'
 	 +'#define BLOCK_NUMBER_OF_SECTOR_TRAILER(sector) (((sector)<NR_SHORTSECTOR)? \n'
   +'((sector)*NR_BLOCK_OF_SHORTSECTOR + NR_BLOCK_OF_SHORTSECTOR-1):\n'
   +'(NR_SHORTSECTOR*NR_BLOCK_OF_SHORTSECTOR + (sector-NR_SHORTSECTOR)*NR_BLOCK_OF_LONGSECTOR + NR_BLOCK_OF_LONGSECTOR-1))\n'
   +'#define BLOCK_NUMBER_OF_SECTOR_1ST_BLOCK(sector) (((sector)<NR_SHORTSECTOR)? \n'
   +'((sector)*NR_BLOCK_OF_SHORTSECTOR):\n'
   +'(NR_SHORTSECTOR*NR_BLOCK_OF_SHORTSECTOR + (sector-NR_SHORTSECTOR)*NR_BLOCK_OF_LONGSECTOR))\n'
   +'(NR_SHORTSECTOR*NR_BLOCK_OF_SHORTSECTOR + (sector-NR_SHORTSECTOR)*NR_BLOCK_OF_LONGSECTOR))\n'
   +'static const uint8_t KEY_DEFAULT_KEYAB[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF};\n'
   +'Adafruit_NFCShield_I2C nfc(IRQ);\n';

  Blockly.Arduino.setups_['setup_NFC'] = ' Serial.begin(115200);\n'
  +'Serial.println("Looking for PN532...");\n'
  +'nfc.begin();\n'
  +'uint32_t versiondata = nfc.getFirmwareVersion();\n'
  +'if (! versiondata) {\n'
  +'Serial.print("Didn"t find PN53x board");\n'
  +'while (1);\n'
  +'}\n'
  +'Serial.print("Found chip PN5"); Serial.println((versiondata>>24) & 0xFF, HEX);\n'
  +'Serial.print("Firmware ver. "); Serial.print((versiondata>>16) & 0xFF, DEC);\n'
  +'Serial.print("."); Serial.println((versiondata>>8) & 0xFF, DEC);\n'
  +'nfc.SAMConfig();\n';

  var code = 'uint8_t success;\n'
  +'uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };\n'
  +'uint8_t uidLength;\n'
  +'bool authenticated = false;\n'
  +'uint8_t blockBuffer[16];\n'
  +'uint8_t blankAccessBits[3] = { 0xff, 0x07, 0x80 };\n'
  +'uint8_t idx = 0;\n'
  +'uint8_t numOfSector = 16;\n'
  +'Serial.println("Place your NDEF formatted Mifare Classic 1K card on the reader");\n'
  +'Serial.println("and press any key to continue ...");\n'
  +'while (!Serial.available());\n'
  +'while (Serial.available()) Serial.read();\n'
  +'success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);\n'
  +'if (success)\n'
  +'{\n'
  +'Serial.println("Found an ISO14443A card/tag");\n'
  +'Serial.print("  UID Length: ");Serial.print(uidLength, DEC);Serial.println(" bytes");\n'
  +'Serial.print("  UID Value: ");\n'
  +'nfc.PrintHex(uid, uidLength);\n'
  +'Serial.println("");\n'
  +'if (uidLength != 4)\n'
  +'{\n'
  +'Serial.println("Ooops ... this doesn"t seem to be a Mifare Classic card!");\n'
  +'return;\n'
  +'}\n'
  +'Serial.println("Seems to be a Mifare Classic card (4 byte UID)");\n'
  +'Serial.println("");\n'
  +'Serial.println("Reformatting card for Mifare Classic (please don"t touch it!) ... ");\n'
  +'for (idx = 0; idx < numOfSector; idx++)\n'
  +'{\n'
  +'success = nfc.mifareclassic_AuthenticateBlock (uid, uidLength, BLOCK_NUMBER_OF_SECTOR_TRAILER(idx), 1, (uint8_t *)KEY_DEFAULT_KEYAB);\n'
  +'if (!success)\n'
  +'{\n'
  +'Serial.print("Authentication failed for sector "); Serial.println(numOfSector);\n'
  +' return;\n'
  +' }\n'
  +'if (idx == 16)\n'
  +'{\n'
  +'memset(blockBuffer, 0, sizeof(blockBuffer));\n'
  +'if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer)))\n'
  +'{\n'
  +' Serial.print("Unable to write to sector "); Serial.println(numOfSector);\n'
  +' return;\n'
  +'}\n'
  +'}\n'
  +'if ((idx == 0) || (idx == 16))\n'
  +'{\n'
  +' memset(blockBuffer, 0, sizeof(blockBuffer));\n'
  +'if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer)))\n'
  +'{\n'
  +' Serial.print("Unable to write to sector "); Serial.println(numOfSector);\n'
  +'return;\n'
  +' }\n'
  +' }\n'
  +'else\n'
  +'{\n'
  +' memset(blockBuffer, 0, sizeof(blockBuffer));\n'
  +'if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 3, blockBuffer)))\n'
  +'{\n'
  +' Serial.print("Unable to write to sector "); Serial.println(numOfSector);\n'
  +' return;\n'
  +'}\n'
  +'if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 2, blockBuffer)))\n'
  +'{\n'
  +'Serial.print("Unable to write to sector "); Serial.println(numOfSector);\n'
  +'return;\n'
  +'}\n'
  +'}\n'
  +'memset(blockBuffer, 0, sizeof(blockBuffer));\n'
  +'if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)) - 1, blockBuffer)))\n'
  +'{\n'
  +'Serial.print("Unable to write to sector "); Serial.println(numOfSector);\n'
  +'return;\n'
  +'}\n'
  +'memcpy(blockBuffer, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB));\n'
  +'memcpy(blockBuffer + 6, blankAccessBits, sizeof(blankAccessBits));\n'
  +'blockBuffer[9] = 0x69;\n'
  +'memcpy(blockBuffer + 10, KEY_DEFAULT_KEYAB, sizeof(KEY_DEFAULT_KEYAB));\n'
  +'if (!(nfc.mifareclassic_WriteDataBlock((BLOCK_NUMBER_OF_SECTOR_TRAILER(idx)), blockBuffer)))\n'
  +'{\n'
  +'Serial.print("Unable to write trailer block of sector "); Serial.println(numOfSector);\n'
  +'return;\n'
  +'}\n'
  +'}\n'
  +'}\n'
  +'Serial.println("\n\nDone!");\n'
  +'delay(1000);\n'
  +'Serial.flush();\n';

  return code;
};


Blockly.Arduino.NFC_Read = function() {
   Blockly.Arduino.definitions_['define_NFCread_include'] = '#include <Wire.h>\n'
 +'#include <Adafruit_NFCShield_I2C.h>\n'
 +' #define IRQ   (2)\n'
 +'Adafruit_NFCShield_I2C nfc(IRQ); \n';
  Blockly.Arduino.setups_['setup_NFCread'] = ' Serial.begin(115200);\n'
 +'Serial.begin(115200);\n'
 +'Serial.println("Hello!");\n'
 +' nfc.begin();\n'
 +' uint32_t versiondata = nfc.getFirmwareVersion();\n'
 +'if (! versiondata) {\n'
 +'  Serial.print("Didn"t find PN53x board");\n'
 +' while (1); // halt\n'
 +' }\n'
 +'  Serial.print("Found chip PN5"); Serial.println((versiondata >> 24) & 0xFF, HEX);\n'
 +' Serial.print("Firmware ver. "); Serial.print((versiondata >> 16) & 0xFF, DEC);\n'
 +'  Serial.print("."); Serial.println((versiondata >> 8) & 0xFF, DEC);\n'
 +' nfc.SAMConfig();\n'
 +' Serial.println("Waiting for an ISO14443A Card ...");\n';
  
  var code = 'uint8_t success;\n'
  +'uint8_t uid[] = { 0, 0, 0, 0, 0, 0, 0 };  // Buffer to store the returned UID\n'
  +'uint8_t uidLength;                        // Length of the UID (4 or 7 bytes depending on ISO14443A card type)\n'
  +'success = nfc.readPassiveTargetID(PN532_MIFARE_ISO14443A, uid, &uidLength);\n'
  +' if (success) {\n'
  +'   delay(200);\n'
  +'    Serial.println("Found an ISO14443A card");\n'
  +'    Serial.print("  UID Length: "); Serial.print(uidLength, DEC); Serial.println(" bytes");\n'
  +'    Serial.print("  UID Value: ");\n'
  +'    nfc.PrintHex(uid, uidLength);\n'
  +'    Serial.println("");\n'
  +'    if (uidLength == 4)\n'
  +'    if (uidLength == 4)\n'
  +'    {\n'
  +'      Serial.println("Seems to be a Mifare Classic card (4 byte UID)");\n'
  +'      Serial.println("Trying to authenticate block 4 with default KEYA value");\n'
  +'      uint8_t keya[6] = {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };\n'
  +'      success = nfc.mifareclassic_AuthenticateBlock(uid, uidLength, 8, 0, keya);\n'
  +'      if (success)\n'
  +'      {\n'
  +'        Serial.println("Sector 2 (Blocks 8..11) has been authenticated");\n'
  +'        uint8_t data[16];\n'
  +'        success = nfc.mifareclassic_ReadDataBlock(8, data);\n'
  +'        if (success)\n'
  +'        {\n'
  +'          Serial.println("Reading Block 8:");\n'
  +'          nfc.PrintHexChar(data, 16);\n'
  +'          Serial.println("");\n'
  +'          delay(1000);\n'
  +'        }\n'
  +'        else\n'
  +'        {\n'
  +'          Serial.println("Ooops ... unable to read the requested block.  Try another key?");\n'
  +'        }\n'
  +'      }\n'
  +'      else\n'
  +'      {\n'
  +'        Serial.println("Ooops ... authentication failed: Try another key?");\n'
  +'      }\n'
  +'    }\n'
  +'    if (uidLength == 7)\n'
  +'    {\n'
  +'      Serial.println("Seems to be a Mifare Ultralight tag (7 byte UID)");\n'
  +'      Serial.println("Reading page 4");\n'
  +'      uint8_t data[32];\n'
  +'      success = nfc.mifareultralight_ReadPage (4, data);\n'
  +'      if (success)\n'
  +'      {\n'
  +'        nfc.PrintHexChar(data, 4);\n'
  +'        Serial.println("");\n'
  +'        delay(1000);\n'
  +'      }\n'
  +'      else\n'
  +'      {\n'
  +'        Serial.println("Ooops ... unable to read the requested page!?");\n'
  +'      }\n'
  +'    }\n'
  +'  }\n'
  +'}\n';
  return code;
};
